﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Pansoft.HIME.Repository;

namespace Pansoft.HIME.Controllers.Attributes
{
    /// <summary>用户权限判断过滤器
    /// </summary>
    public class StaffAuthorizeAttribute : AuthorizationFilterAttribute 
    {
        /// <summary>用户权限判断过滤器
        /// </summary>
        /// <param name="authNumber">权限编号</param>
        public StaffAuthorizeAttribute(int authNumber)
        {
            AuthNumber = authNumber;
        }

        /// <summary>权限编号
        /// </summary>
        public int AuthNumber { get; protected set; }

        /// <summary>重写权限的的判断主方法，以判断用户的角色是否对指定的功能拥有权限
        /// </summary>
        /// <param name="context"></param>
        public override void OnAuthorization(HttpActionContext context)
        {
            base.OnAuthorization(context);
            bool hasAuth = false;
            HttpCookieCollection cookies = HttpContext.Current.Request.Cookies;
            //从Cookie中取出登录员工的角色，根据角色判断该角色是否能够访问这个Action
            if (cookies.AllKeys.Contains("StaffRoleId"))
            {
                HttpCookie r = cookies["StaffRoleId"];
                if (r != null)
                {
                    //从cookie中取得角色编号
                    string role = r.Value;
                    hasAuth = RepositoriesFactory.Instance.AuthorityRepository.ContainsAuthInRole(role, AuthNumber);
                }
            }
            //判断用户是否登录
            if (!hasAuth)
            {
                context.Response = context.Request.CreateResponse(HttpStatusCode.Forbidden);
                context.Response.ReasonPhrase = "UnAuthorized";
            }
        }

    }
}